/**
 * Diplomova prace
 * - nastaveni internetove pripojeni pomoci GPRS
 * - otevreni spojeni HTTP
 * - nacteni testovaci stranky - stranka, kde se zaznamenava pristup (moznost zpetne overit spravne pripojeni)
 * - ulozeni odpovedi a jeji tisk na COM port
 * - naznak prace s DB pomoci servletu - zatim servlet neni nainstalovan 
 */
package tcinert;

import com.siemens.icm.io.ATCommand;
import com.siemens.icm.io.ATCommandFailedException;
import com.siemens.icm.io.ATCommandResponseListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Calendar;
import java.util.Date;
import javax.microedition.io.CommConnection;
import javax.microedition.io.Connection;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.InputConnection;
import javax.microedition.io.OutputConnection;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;

/**
 * @version 0.5
 * @author Tomas Cinert
 */
public class Diplomka extends MIDlet
{
  ATCommand at;
  ATCommandResponseListener listener;
  String kvalita;
  InputStream input;
  
  CommConnection spojeni;
  OutputStream output;
  RecordStore databaze;
 
  
  /**
  * Konstruktor 
   * - incializace promenne AT Command, osetreni vyjimek 
   * - vytvoreni spojeni se seriovym portem, nastaveny parametry a odeslani potvrzovaci zpravy
   **/
  public Diplomka()
  {
    try
    {
      at = new ATCommand(false);
     
    } catch (ATCommandFailedException ex) {
      ex.printStackTrace();
    } catch (IllegalStateException ex) {
      ex.printStackTrace();
    }
    listener = new ATCommandResponseListener()         // Listener na odezvu na ATprikazy
    {
      public void ATResponse(String Response) {
        zapisCOM(Response);
        if (Response.startsWith("+CSQ", 2))
        {
           kvalita = Response;
        }

        if (Response.startsWith("ERROR", 2)) {
          
            destroyApp(true);
           notifyDestroyed();
        }
        else if (Response.startsWith("+CREG:", 2))
        {
          if (!Response.startsWith("+CREG: 0,1", 2)) {
            ATsend("AT+CMGS=\"+420604450956\"\r");
            ATsend("Konfigurace selhala: \032");
            destroyApp(true);
            notifyDestroyed();
          }
        }
      }
    };
    
    try
    { // Vytvoreni spojeni na portu COM0 s rychlosti 115200 pro Cteni/Zapis s povolenym timeoutem - pokud dojde k preteceni je generovana vyjimka
      spojeni = ((CommConnection)Connector.open("comm:COM0;baudrate=115200", 3, true));
      input = spojeni.openInputStream();
      output = spojeni.openOutputStream();
      String zprava = "Spojeni otevreno";
      zapisCOM(zprava);
    }
    catch (IOException ex) {
      destroyApp(true);
      notifyDestroyed();
    }
  }
  /**
   * Metoda na poslani AT prikazu
   * - po odeslani je vlakno uspano na 1 sekundu z duvodu cekani na vykonani prikazu,
   *  jelikoz je pouzita neblokujici varianta metody send
   */
  public void ATsend(String ATprikaz)
  {
    try
    {
      at.send(ATprikaz, listener);
      Thread.sleep(1000L);
    } catch (InterruptedException ex) {
      ex.printStackTrace();
    } catch (ATCommandFailedException ex) {
      ex.printStackTrace();
    } catch (IllegalStateException ex) {
      ex.printStackTrace();
    } catch (IllegalArgumentException ex) {
      ex.printStackTrace();
    }
  }
  /**
   * Metoda na zapis dat na seriovy port
   *@param zprava
   */
  public void zapisCOM(String zprava)
  {
    try
    {
      output.write(zprava.getBytes());
    }
    catch (IOException e)
    {
    }
  }
  
  
  /**
   * Spousteci metoda MIDletu 
   * - je volana po spusteni MIDletu 
   **/
  public void startApp()
  {
        HttpConnection con=null;
        InputStream iStr = null;
        int length;
        String odpoved;
        /*
         * Ukazka prace s DB pomoci servletu - uloxeni tri parametru
         * String url ="http://localhost/test-app/test1" + "?" +"param1=" + "54" + "&" +"param2=" + "55" + "&" + "param3=" + "56";
         * con=(HttpConnection) Connector.open(url);
         * con.setRequestMethod(HttpConnection.GET); 
         */
        ATsend("AT^SJNET=\"gprs\",\"wap.t-mobile.cz\",\"wap\",\"wap\",,0\r");
        try {
            con=(HttpConnection) Connector.open("http://test.webingenia.com/ThisIsMe");  // Otevreni spojeni
            con.setRequestMethod(HttpConnection.GET);       // Zaslan pozadavek
            iStr=con.openInputStream();         // Otevreni vstupniho streamu
            if (con.getResponseCode() == HttpConnection.HTTP_OK)        // Pokud spojeni probehlo v poradku
            {
            length = (int) con.getLength();         // Nacteni delky odpovedi
            byte data[] = new byte[length];
            iStr.read(data);             // Nacteni dat
            
            odpoved = new String(data);     // Prevedeni na String
            zapisCOM(odpoved);      // Tisk na COM port
            }
            iStr.close();
            con.close();
            zapisCOM("Je tu konec");
            input.close();
            output.close();
            spojeni.close();
            destroyApp(true);
            notifyDestroyed();
        
        } catch (IOException ex) {
            zapisCOM(ex.toString());
         }
    
       destroyApp(true);
       notifyDestroyed(); 
    
  }

  public void pauseApp()
  {
  }
  
  
  public void destroyApp(boolean unconditional) {
      
  }
}